/*
* Powered By [choudou5]
* Web Site: http://www.hsolr.com
* License：MIT
* Since 2018 - 2020
*/
package com.choudou5.solr.service.sys;

import com.choudou5.solr.annotation.ServiceInfo;
import com.choudou5.solr.bean.sys.SysNoticeBean;
import com.choudou5.solr.framework.constants.CacheConsts;
import com.choudou5.solr.framework.constants.SysConsts;
import com.choudou5.solr.framework.holder.SysContextHolder;
import com.choudou5.solr.service.BaseService;
import com.choudou5.solr.util.DateUtil;
import com.choudou5.solr.util.cache.CacheFactory;
import com.choudou5.solr.util.cache.impl.LRUCache;
import com.choudou5.solr.util.exception.BizException;
import com.choudou5.solr.util.jdbc.SqlFormatUtil;

import java.util.Date;

/**
 * @name：系统公告表 Service
 * @author：choudou5
 * @date：2018-07-28
 */
@ServiceInfo(table = "solr_sys_notice", desc = "系统公告表")
public class SysNoticeService extends BaseService<SysNoticeBean> {

    private static final LRUCache<String, SysNoticeBean> CACHE = CacheFactory.newLRUCache(10);
    public static final String HAS_SYS_NOTICE = "hasSysNotice";

    @Override
    public void save(SysNoticeBean sysNoticeBean) throws BizException {
        super.save(sysNoticeBean);
        CACHE.remove(CacheConsts.NOTICE_LAST);
    }

    public SysNoticeBean getLast() throws BizException {
        SysNoticeBean notice = CACHE.get(CacheConsts.NOTICE_LAST);
        if(notice != null)
            return notice;
        String now = DateUtil.now();
        String where = "status = 1 AND start_time < ? AND end_time > ? ORDER BY create_time DESC";
        where = SqlFormatUtil.format(where, now, now);
        notice = findOne(where);
        if(notice == null) {
            SysContextHolder.setParam(HAS_SYS_NOTICE, false);
            return null;
        }
        long diff = DateUtil.betweenMs(new Date(), notice.getEndTime());
        CACHE.put(CacheConsts.NOTICE_LAST, notice, diff);
        SysContextHolder.setParam(HAS_SYS_NOTICE, true);
        return notice;
    }

    public void offlineNotice(Integer id) throws BizException {
        SysNoticeBean notice = new SysNoticeBean(id);
        notice.setStatus(SysConsts.STATUS_N);
        updateByNonNull(notice);
        CACHE.remove(CacheConsts.NOTICE_LAST);
    }

}